package com.jrzh.security;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.jrzh.entity.Role;
import com.jrzh.entity.User;
import com.jrzh.repository.UserRepository;

/**
 * 自定义用户认证
 * @author Xanthin
 *
 */
@Component
public class CustomUserDetailsService implements UserDetailsService,Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 4262979088866867793L;
	@Autowired
	private UserRepository userRepository;
	/**
	 * 重载loadUserByUsername方法，并返回自定义的SecurityUser
	 * 通过SecurityUser来完成用户的身份认证
	 */
	@Override
	public UserDetails loadUserByUsername(String userName)
			throws UsernameNotFoundException {
		System.out.println(">>>>>>>查找用户>>>>>"+userName);
		User user = userRepository.findByName(userName);
		System.out.println("得到用户为："+user);
		if(user == null){
			throw new UsernameNotFoundException("用户 【"+userName+"】"+"不存在");
		}
		List<String> roleNames = new ArrayList<String>();
		List<Role> roles = user.getRoles();
		if(roles.size() > 0){
			for(Role role : roles){
				roleNames.add(role.getName());
			}
		}
		SecurityUser securityUser = new SecurityUser(user.getId(),user.getName(),user.getPassword(),roleNames);
		System.out.println(securityUser);
		return securityUser;
	}

}
